<?php
namespace app\admin\controller\agent;
use app\admin\controller\Controller;
use app\admin\model\agent\User as UserModel;
use app\admin\model\agent\Agent as AgentModel;
use think\Session;
use think\Db;
/**
 * 客户列表
 */
class Agent extends Controller{
    protected  $model;
    public function _initialize(){
        parent::_initialize();
        $this->model=new AgentModel();
    }
    /**
     * 客户列表首页
     */
    public function index(){
        $loginInfo=Session::get('yoshop_adminuser');
        //根据当前登录公司类型获取数据
        $companyId=[];
        $companyInfo=Db::name('yonghui_company')->where(['id'=>$loginInfo['user']['company_id']])->find();
        if($loginInfo['user']['type']==1){
            //总后台
            $companyId[]=0;
            $buildList=Db::name('yonghui_building')->where(['status'=>1])->field('id,name')->select();
        }elseif($loginInfo['user']['type']==2){
            //自营公司
            $com=Db::name('yonghui_company')->where(['upId'=>$companyInfo['id']])->select();
            if($com){
                foreach($com as $k=>$v){
                    $companyId[]=$v['id'];
                }
                $companyId[]=$loginInfo['user']['company_id'];
            }else{
                $companyId[]=$loginInfo['user']['company_id'];
            }
            $buildList=Db::name('yonghui_building')->where(['companyId'=>['in',$loginInfo['user']['company_id']],'status'=>1])->field('id,name')->select();
        }else{
            //渠道公司
            $companyId[]=$loginInfo['user']['company_id'];
            $com=Db::name('yonghui_company')->where(['id'=>$loginInfo['user']['company_id']])->field('id,upId')->find();
            $buildList=Db::name('yonghui_building')->where(['companyId'=>$com['upId'],'status'=>1])->field('id,name')->select();
        }
        //获取当前公司项目组
        $project=Db::name('yonghui_project')->where(['companyId'=>$loginInfo['user']['company_id'],'status'=>1])->select();
        //获取楼盘列表
        //var_dump($this->model->getList($this->request->param(),$companyId)->toArray());
        $list=$this->model->getList($this->request->param(),$companyId);
        return $this->fetch('index', [
            'list' =>$list,
            'buildlist'=>$buildList,
            'project'=>$project
        ]);
    }
    /**
     * 客户列表数据导出
     */
    public function goodsExport(){
        if (!$this->goodsFinanceExport($order_source = 10,$this->request->param())) {
            return $this->renderError('操作失败');
        }
        return $this->goodsFinanceExport($order_source = 10,$this->request->param());
    }
    public function goodsFinanceExport($order_source,$query = [])
    {
        header("Content-type:text/html;charset=utf-8");
        $mpName = '客户列表';
        $limit = 500;//每次只从数据库取50000条以防变量缓存太大
        // buffer计数器
        $cnt = 0;
        set_time_limit(0);
        //计算总的数据
        $sqlCount = $this->getGoodsFinanceExport($order_source,$query,0, $limit,true);

        if($sqlCount<1){
            $this->error = '无数据导出';
            return false;
        }

        $xlsTitle = [
            '客户id', '录入人', '录入人电话', '客户名称', '客户电话', '跟进人', '跟进人电话', '意向楼盘名称', '状态',
            '添加时间',
        ];


        $fileName = 'customerList';// 文件名称可根据自己情况设定
        // 输出Excel文件头，可把user.csv换成你要的文件名
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        $fileNameArr = array();
        // 逐行取出数据，不浪费内存
        for ($i = 0; $i < ceil($sqlCount / $limit); $i++) {

            $fp = fopen($fileName . '_' . $i . '.csv', 'w'); //生成临时文件
            fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
            // chmod('attack_ip_info_' . $i . '.csv',777);//修改可执行权限
            $fileNameArr[] = $fileName . '_' . $i . '.csv'; // 将数据通过fputcsv写到文件句柄
            fputcsv($fp, $xlsTitle);
            $start = $i * $limit;
            $dataArr = $this->getGoodsFinanceExport($order_source,$query, $start, $limit,false);

            foreach ($dataArr as $a) {
                $cnt++;
                if ($limit == $cnt) {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                fputcsv($fp, $a);
            }
            fclose($fp);  //每生成一个文件关闭
        }

        //进行多个文件压缩
        $zip = new \ZipArchive();
        $filename = $fileName . ".zip";
        $zip->open($filename, $zip::CREATE);   //打开压缩包
        foreach ($fileNameArr as $file) {
            $zip->addFile($file, basename($file));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        foreach ($fileNameArr as $file) {
            unlink($file); //删除csv临时文件
        }

        //输出压缩文件提供下载
        header("Cache-Control: max-age=0");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名
        header("Content-Type: application/zip"); // zip格式的
        header("Content-Transfer-Encoding: binary"); //
        header('Content-Length: ' . filesize($filename)); //
        @readfile($filename);//输出文件;
        unlink($filename); //删除压缩包临时文件

    }
    public function getGoodsFinanceExport($order_source,$query = [],$start, $limit,$count = false){
        $loginInfo=Session::get('yoshop_adminuser');
        //根据当前登录公司类型获取数据
        $companyId=[];
        $companyInfo=Db::name('yonghui_company')->where(['id'=>$loginInfo['user']['company_id']])->find();
        if($loginInfo['user']['type']==1){
            //总后台
            $companyId[]=0;
        }elseif($loginInfo['user']['type']==2){
            //自营公司
            $com=Db::name('yonghui_company')->where(['upId'=>$companyInfo['id']])->select();
            if($com){
                foreach($com as $k=>$v){
                    $companyId[]=$v['id'];
                }
                $companyId[]=$loginInfo['user']['company_id'];
            }else{
                $companyId[]=$loginInfo['user']['company_id'];
            }
        }else{
            //渠道公司
            $companyId[]=$loginInfo['user']['company_id'];
        }
        if($count==true){
            //获取数据列表
            if($companyId[0]!=0){
                return Db::name('yonghui_customer')->where('sourceId', 'in',$companyId)->count();
            }else{
                return Db::name('yonghui_customer')->count();
            }
        }
        // 获取数据列表
        if($companyId[0]!=0){
            $list =  Db::name('yonghui_customer')->where('sourceId', 'in',$companyId)->select();
        }else{
            $list =  Db::name('yonghui_customer')->select();
        }
        // 表格内容
        $dataArray = [];
        foreach ($list as $order) {
            //1:跟进中 2：已失效 3：已付订 4：已签约
            if($order['followStatus']==1){
                $str='跟进中';
            }
            if($order['followStatus']==2){
                $str='已失效';
            }
            if($order['followStatus']==3){
                $str='已付订';
            }
            if($order['followStatus']==4){
                $str='已签约';
            }
            $dataArray[] = [
                '客户id' => $order['id'],
                '录入人' => getluruname($order['inputId']),
                '录入人电话' =>getluruphone($order['inputId']),
                '客户名称' => $order['name'],
                '客户电话' =>$order['phone'],
                '跟进人' => getluruname($order['followUserId']),
                '跟进人电话' => getluruphone($order['followUserId']),
                '意向楼盘名称' => getgenjloupanname($order['propertiesId']),
                '状态' => $str,
                '添加时间' =>date('Y-m-d H:i:s',$order['createTime']),
            ];
        }
        return  $dataArray;
    }

    /**
     * 获取跟进信息
     */
    public function getContent(){
        $id=input('post.id');
        $imageids=Db::name('yonghui_follow')->where(['customerId'=>$id])->select()->toArray();
        if($imageids){
            foreach($imageids as $k=>$v){
                $arr=[];
                $imageInfos=Db::name('upload_file')->where('file_id','in',json_decode($v['imageIds'],true))->select()->toArray();
                if($imageInfos){
                    foreach($imageInfos as $k1=>$v1){
                        $arr[]=$v1['file_url'].'/'.$v1['file_name'];
                    }
                }
                $imageids[$k]['imageInfo']=$arr;
                $imageids[$k]['createTime']=date('Y-m-d H:i:s',$imageids[$k]['createTime']);
                $imageids[$k]['upUser']=Db::name('yonghui_user')->where(['id'=>$v['userId']])->field('id,name')->find()['name'];
            }
        }
        return json(['msg'=>'获取成功','code'=>'success','data'=>$imageids]);
    }
}